package com.zlsy.secondtime.deadlock;

import java.util.concurrent.TimeUnit;

/**
 * @author zhouliang
 * @date 2020/6/17 16:39
 */
public class MustDeadLock implements Runnable {
    int flag = 1;
    private final static Object object1 = new Object();
    private final static Object object2 = new Object();

    @Override
    public void run() {
        if (flag == 1) {
            synchronized (object1) {
                System.out.println(1);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (object2) {
                    System.out.println(2);
                }
            }
        }

        if (flag == 2) {
            synchronized (object2) {
                System.out.println(3);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (object1) {
                    System.out.println(4);
                }
            }
        }
    }

    public static void main(String[] args) {

        MustDeadLock mustDeadLock1 = new MustDeadLock();
        MustDeadLock mustDeadLock2 = new MustDeadLock();

        mustDeadLock1.flag = 1;
        mustDeadLock2.flag = 2;

        Thread a = new Thread(mustDeadLock1);
        Thread b = new Thread(mustDeadLock2);

        a.start();
        b.start();
    }
}
